import router from '@/router'
import store from '@/store'
import getPageTitle from '@/utils/get-page-title'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      // 有token，还去登录 ---> 直接去主页
      next('/')
      NProgress.done()
    } else {
      // 1. 获取个人信息
      // if (没有userId) {
      // if (!store.state.user.userInfo.userId) {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    // 没有token，只能访问白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
    // whiteList.includes(to.path) ? next() : next('/login')
  }
  console.log(token, '路由跳转', from.path, '----->', to.path)
})

router.afterEach(() => {
  NProgress.done()
})
